import {UserInfoApi} from "@/configs/controller";

/**
 * 用户信息
 */
export class UserInfo {
  constructor() {
    this.init();
  }

  init(isClear) {
    this.token = "";
    this.expire = 0;
    this.uid = 0;
    this.uname = "";
    this.mobile = "";
    this.role = 0;
    this.permittedRoutes = [];
    if (isClear) {
      localStorage.removeItem("token");
    }
  }

  save() {
    if (typeof this.token === "string" && typeof this.expire === "number") {
      localStorage.setItem("token", this.token);
      localStorage.setItem("expire", this.expire);
    } else {
      // eslint-disable-next-line no-console
      console.error("token 或 expire 类型错误，存储失败");
    }
  }

  async load() {
    const token = localStorage.getItem("token");
    const expire = localStorage.getItem("expire");
    this.token = token;
    this.expire = Number(expire);
    if (typeof this.token === "string" && !Number.isNaN(this.expire)) {
      try {
        const api = new UserInfoApi().auth(token);
        await api.send();
        const {data} = await api.getDatas();
        this.uid = data.id;
        this.uname = data.username;
        this.mobile = data.mobile;
        this.role = data.roles_id;
        this.permittedRoutes = [
          "/",
        ];
        return true;
      } catch {
        return false;
      }
    } else {
      return false;
    }
  }
}
